package com.ruoyi.framework.config.properties;

import com.ruoyi.common.annotation.Anonymous;
import org.apache.commons.lang3.RegExUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 设置Anonymous注解允许匿名访问的url，并支持从配置文件中加载额外的匿名URL
 */
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
    private ApplicationContext applicationContext;

    // 新增：从配置文件中读取额外的匿名URL（对应application.yml中的ruoyi.security.permit-urls）
    @Value("${ruoyi.security.permit-urls:}")
    private List<String> configPermitUrls = new ArrayList<>();

    private List<String> urls = new ArrayList<>();
    public String ASTERISK = "*";

    @Override
    public void afterPropertiesSet() {
        // 1. 扫描@Anonymous注解获取URL（原有逻辑）
        scanAnonymousAnnotations();
        // 2. 加载配置文件中的额外URL（新增逻辑）
        loadConfigPermitUrls();
    }

    /**
     * 扫描@Anonymous注解标记的控制器和方法（原有逻辑）
     */
    private void scanAnonymousAnnotations() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);

            // 处理方法上的@Anonymous注解
            Anonymous methodAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class);
            processAnnotation(methodAnnotation, info);

            // 处理类上的@Anonymous注解
            Anonymous controllerAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class);
            processAnnotation(controllerAnnotation, info);
        });
    }

    /**
     * 处理注解并提取URL（原有逻辑优化）
     */
    private void processAnnotation(Anonymous annotation, RequestMappingInfo info) {
        if (annotation != null) {
            info.getPatternsCondition().getPatterns()
                    .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)));
        }
    }

    /**
     * 加载配置文件中的额外匿名URL（新增逻辑）
     */
    private void loadConfigPermitUrls() {
        if (!configPermitUrls.isEmpty()) {
            // 直接添加配置文件中的URL（支持通配符如/**，无需替换路径变量）
            urls.addAll(configPermitUrls);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.applicationContext = context;
    }

    public List<String> getUrls() {
        return urls;
    }

    public void setUrls(List<String> urls) {
        this.urls = urls;
    }
}
